//
//  HomeViewController.m
//  ZhengTuo
//
//  Created by sunliang on 2018/1/26.
//  Copyright © 2018年 ZhengTuoKEJI. All rights reserved.
//

#import "HomeViewController.h"
#import "CTQGListVC.h"
#import "CTQGDefaultCell.h"
//#import "CTQGFirstCell.h"
//#import "CTQGSecondCell.h"
#import "HomeNetManager.h"
#import "CEAssetInfoModel.h"
#import "MineNetManager.h"

#import "GetCoinVC.h"
#import "CETransformVC.h"
#import "JHUIAlertView.h"
#import "CTFinanceTransformVC.h"

@interface HomeViewController ()<UITextFieldDelegate>
{
    UILabel *zongZiChanLB;
}
 @property (nonatomic, strong) CETransformVC *transformVC;
@property (nonatomic,copy) NSMutableArray *contentArr;

@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, copy) NSString *coinId;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) JHUIAlertView *alertView;
    
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.viewTitle.text = LocalizationKey(@"Wallet");
    
    [self setTablewViewHeard];
    [self headRefreshWithScrollerView:self.tableView];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
}

//- (void)viewWillLayoutSubviews {
//    [super viewWillLayoutSubviews];
//    self.tableView.frame = self.view.bounds;
//}

#pragma mark-下拉刷新数据
- (void)refreshHeaderAction {
    [self getUserAssetInfo];
}
 
    
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    if(![YLUserInfo isLogIn]) {
        [self showLoginViewController];
    }
    else {
        
        [self getUserAssetInfo];
    }
}

-(void)setTablewViewHeard {
    UIImageView *bgImage = [[UIImageView alloc]initWithFrame:CGRectMake(-15, 0, kWindowW+30, 170+SafeAreaNavTopHeight+(SafeAreaNavTopHeight+20))];
       [self.view addSubview:bgImage];
       bgImage.backgroundColor = tMainColor;
       UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bgImage.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(80.0, 80.0)];
       CAShapeLayer *maskLayer = [CAShapeLayer layer];
       maskLayer.frame = bgImage.bounds;
       maskLayer.path = maskPath.CGPath;
       bgImage.layer.mask = maskLayer;
    
    UIImageView *zImage = [[UIImageView alloc]init];
    [bgImage addSubview:zImage];
    [zImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(22);
        make.centerY.equalTo(0);
    }];
    zImage.image = ImageName(@"z_zichan_head");
    
    zongZiChanLB = [[UILabel alloc]init];
    [zImage addSubview:zongZiChanLB];
    [zongZiChanLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(zImage.mas_right).offset(13);
        make.centerY.equalTo(zImage);
    }];
    zongZiChanLB.textColor = [UIColor whiteColor];
    zongZiChanLB.font = kFont(16);
    zongZiChanLB.numberOfLines = 0;
    
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 125;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.tableView registerClass:[CTQGDefaultCell class] forCellReuseIdentifier:@"qgdefaultcell"];
    
    CGRect rect    = self.view.bounds;
       rect.origin.y += (SafeAreaNavTopHeight+20+129);
    rect.origin.x = 12;
       rect.size.height    -= (SafeAreaNavTopHeight+20+kTabBarHeight+129);
    rect.size.width = (kWindowW-28);
       self.tableView.frame = rect;
    
    self.tableView.tableFooterView = [UIView new];
    if (@available(iOS 11.0, *)){
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;//防止刷新指定行时，偏移量改变
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.contentArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        
    CTQGDefaultCell *cell = [CTQGDefaultCell createTableView:tableView];
    [cell.rechargeBtn setTitle:LocalizationKey(@"Recharge") forState:UIControlStateNormal];
    [cell.redrawBtn setTitle:LocalizationKey(@"Withdraw") forState:UIControlStateNormal];
    [cell.exchangeBtn setTitle:LocalizationKey(@"Convert") forState:UIControlStateNormal];
    [cell.financeBtn setTitle:LocalizationKey(@"Finance") forState:UIControlStateNormal];
        
    CEAssetInfoModel *infoModel = self.contentArr[indexPath.row];
    cell.frozenCoin.text  = [NSString stringWithFormat:@"%@：%@",LocalizationKey(@"Frozen"),[ToolUtil judgeStringForDecimalPlaces:infoModel.amountFrozen point:4]];
    cell.canUsedCoin.text = [NSString stringWithFormat:@"%@：%@",LocalizationKey(@"Available"),[ToolUtil judgeStringForDecimalPlaces:infoModel.amount point:4]];
    cell.coinName.text = infoModel.coinName;
    [cell.titleImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMAGE,infoModel.coinLogo]] placeholderImage:[UIImage imageNamed:@"announce"]];
        
    __weak typeof(self)weakself = self;
    cell.rechargeBlock = ^{
        [weakself rechargeWithCoinId:infoModel.coinId address:infoModel.address coinNameStr:infoModel.coinName];
    };
    cell.redrawBlock = ^{
        [weakself withdrawWithCoinId:infoModel.coinId fee:[infoModel.fee stringValue] coinName:infoModel.coinName balance:infoModel.amount];
    };
    
    cell.exchangeBlock = ^{
        if ([infoModel.supportExchange boolValue] == 0) {
            [self.view makeToast:LocalizationKey(@"coming soon") duration:1 position:CSToastPositionCenter];
            return ;
        }
        [weakself doExchangeWithModel:infoModel];
    };
    
    cell.financeBlock = ^{
//        if ([infoModel.supportFinanc boolValue] == 0) {
//            [self.view makeToast:LocalizationKey(@"coming soon") duration:1 position:CSToastPositionCenter];
//            return ;
//        }
       
        CTFinanceTransformVC *vc = [[CTFinanceTransformVC alloc] init];
        vc.unit = infoModel.coinId;
        vc.canusedBalance = [ToolUtil judgeStringForDecimalPlaces:infoModel.amount point:4];
        vc.financingCnt  = [ToolUtil judgeStringForDecimalPlaces:[infoModel.financingCnt stringValue] point:4];
        vc.hidesBottomBarWhenPushed = YES;
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    
    return cell;
}
    
- (void)withdrawWithCoinId:(NSString *)coinId fee:(NSString *)fee coinName:(NSString *)coinName balance:(NSString *)balance {
    CETransformVC *vc = [[CETransformVC alloc] init];
    vc.unit = coinId;
    vc.coinName = coinName;
    vc.fee  = fee;
    vc.canusedBalance = balance;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
    
- (void)rechargeWithCoinId:(NSString *)coinId address:(NSString *)address coinNameStr:(NSString *)coinNameStr {
    GetCoinVC *vc = [[GetCoinVC alloc] init];
    vc.unit = coinId;
    vc.address = address;
    vc.coinNameStr = coinNameStr;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
    
- (void)getUserAssetInfo {
//    [EasyShowLodingView showLodingText:LocalizationKey(@"loading")];
    [HomeNetManager getUserAssetInfo:[YLUserInfo shareUserInfo].ID CompleteHandle:^(id resPonseObj, int code) {
        [EasyShowLodingView hidenLoding];
        if (code) {
            [self.contentArr removeAllObjects];
            
            NSInteger codeInt = [resPonseObj[@"code"] integerValue];
            NSDictionary *data = resPonseObj[@"data"];
            zongZiChanLB.text = [NSString stringWithFormat:@"%@\n$%@",LocalizationKey(@"总资产"),data[@"totalAsset"]];

            NSArray *temWalletExt = data[@"list"];
            if (codeInt == 0) {
                for (NSDictionary *subdic in temWalletExt) {
                    CEAssetInfoModel *infoModel = [CEAssetInfoModel mj_objectWithKeyValues:subdic];
                    if ([infoModel.isDisplay isEqualToString:@"1"]) {
                        [self.contentArr addObject:infoModel];
                    }
                }
                [self.tableView reloadData];
            }
            else {
                if (codeInt == -1000001) {
                    [ShowLoGinVC showLoginVc:self withTipMessage:resPonseObj[MESSAGE]];
                }
            }
        }
        else {
            [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}
 
- (void)closeView {
    [self.view endEditing:YES];
    self.textField.text = @"0";
    [self.alertView dismiss];
}
    
//兑换
- (void)doExchangeWithModel:(CEAssetInfoModel *)model {
    
    self.coinId = model.coinId;
    
    JHUIAlertConfig *config = [[JHUIAlertConfig alloc] init];
    
    config.title.text  = LocalizationKey(@"Exchange");
    config.title.color = [UIColor colorWithHEX:maincolor];
    config.title.bottomPadding = 100;
    config.dismissWhenTapOut   = NO;
    config.contentViewWidth    = SCREEN_WIDTH*0.8;
    config.contentViewHeight   = 180;
    self.alertView = [[JHUIAlertView alloc] initWithConfig:config];
    
    __weak typeof(self)weakself = self;
    [self.alertView addCustomView:^(JHUIAlertView *alertView, CGRect contentViewRect, CGRect titleLabelRect, CGRect contentLabelRect) {
        
        UIButton *closebtn = [UIButton buttonWithType:UIButtonTypeCustom];
        closebtn.tintColor = [UIColor blackColor];
        [closebtn setImage:[UIImage imageNamed:@"loginClose"] forState:UIControlStateNormal];
        [closebtn addTarget:weakself action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
        closebtn.frame = CGRectMake(contentViewRect.size.width-30, 10, 20, 20);
        [alertView.contentView addSubview:closebtn];
        
        UIView *textView = [[UIView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(titleLabelRect)+24, contentViewRect.size.width-30, 40)];
        textView.backgroundColor = [UIColor colorWithHEX:@"EAEAEA"];
        textView.layer.cornerRadius = 5;
        [alertView.contentView addSubview:textView];
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(22, CGRectGetMaxY(titleLabelRect)+24, contentViewRect.size.width-44, 40)];
        textField.keyboardType = UIKeyboardTypeDecimalPad;
        textField.layer.cornerRadius = 5;
        [alertView.contentView addSubview:textField];
        weakself.textField = textField;
        weakself.textField.placeholder = [NSString stringWithFormat:@"%@:%@",LocalizationKey(@"Available"),[model.balance stringValue]];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(15, CGRectGetMaxY(textField.frame)+24, contentViewRect.size.width-30, 40);
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button setTitle:LocalizationKey(@"Confirm") forState:0];
        [button setTitleColor:[UIColor whiteColor] forState:0];
        button.layer.cornerRadius = 5;
        button.backgroundColor = [UIColor colorWithHEX:maincolor];
        [button addTarget:weakself action:@selector(buttonEvent) forControlEvents:1<<6];
        [alertView.contentView addSubview:button];
        
    }];
    
    [self.view addSubview:self.alertView];
}
    
- (void)buttonEvent {
    if ([self.textField.text floatValue] <= 0) {
        return;
    }
    [self.view endEditing:YES];
    [self.alertView dismiss];
    
    NSDictionary *dic = @{@"userId":[YLUserInfo shareUserInfo].ID,
                          @"coinId":self.coinId,
                          @"value":self.textField.text
                          };
    __weak typeof(self)weakself = self;
    [EasyShowLodingView showLodingText:LocalizationKey(@"loading")];
    [HomeNetManager getdoExchangeInfo:dic CompleteHandle:^(id resPonseObj, int code) {
        self.textField.text = @"0";
        [EasyShowLodingView hidenLoding];
        if (code) {
            [weakself.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            NSInteger codeInt = [resPonseObj[@"code"] integerValue];
            if (codeInt == 0) {
                [self.tableView reloadData];
            }
            
            if (codeInt == -1000001) {
                [ShowLoGinVC showLoginVc:self withTipMessage:resPonseObj[MESSAGE]];
            }
            
        }
        else {
            [weakself.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}
    
- (NSMutableArray *)contentArr
{
    if (!_contentArr) {
        _contentArr = [NSMutableArray array];
    }
    return _contentArr;
}


@end
